<template>
	<div class="page-container">
		<div style="margin: 20px 0">
			<el-button type="primary" @click="addBanner">添加轮播图</el-button>
		</div>
		<el-table :data="banners" style="width: 100%">
			<el-table-column type="index" width="50" label="ID" />

			<el-table-column prop="url" label="图片" min-width="240">
				<template #default="scope">
					<img
						v-if="scope.row.url"
						:src="'http://localhost:3000/' + scope.row.url"
						alt=""
						style="width: 200px; height: 200px"
					/>
					<el-tag v-else type="danger">暂未上传</el-tag>
				</template>
			</el-table-column>
			<el-table-column label="操作">
				<template #default="scope">
					<el-button type="danger" @click="delBanner(scope.row)"
						>删除</el-button
					>
				</template>
			</el-table-column>
		</el-table>

		<el-dialog
			v-model="dialogInfo.visible"
			:title="dialogInfo.title"
			width="30%"
			:close-on-click-modal="false"
			:destroy-on-close="true"
		>
			<el-upload
				action="http://localhost:3000/api/banner/upload"
				list-type="picture-card"
				:limit="1"
				:on-success="handleUploadBannerSuccess"
			>
				<el-icon>
					<Plus />
				</el-icon>
			</el-upload>
		</el-dialog>
	</div>
</template>

<script setup>
import { onMounted, reactive, ref } from "vue";
import { list, add, update, del } from "@/api/banner.js";

import { ElMessage } from "element-plus";

const banners = ref([]);
const dialogInfo = reactive({
	title: "添加轮播图",
	visible: false,
	type: 0,
});

onMounted(() => {
	getBanners();
});

const getBanners = async () => {
	try {
		const res = await list();
		banners.value = res.result;
	} catch (err) {
		console.error(err);
	}
};

const addBanner = () => {
	dialogInfo.type = 0;
	dialogInfo.title = "添加轮播图";
	dialogInfo.visible = true;
};

const handleUploadBannerSuccess = () => {
	dialogInfo.visible = false;
	getBanners();
};

const delBanner = async row => {
	await del({
		id: row.id,
	});
	ElMessage.success("删除成功");
	getBanners();
};
</script>
<style scoped>
.avatar-uploader .avatar {
	width: 178px;
	height: 178px;
	display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
	border: 1px dashed var(--el-border-color);
	border-radius: 6px;
	cursor: pointer;
	position: relative;
	overflow: hidden;
	transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
	border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
	font-size: 28px;
	color: #8c939d;
	width: 178px;
	height: 178px;
	text-align: center;
}
</style>
